<?php

namespace App\Console\Commands;

use App\Http\Controllers\App\MemberOrderController;
use App\Models\MemberOrder;
use Illuminate\Console\Command;
use Yansongda\Pay\Pay;

/**
 * 异步支付回调
 * Class StaffIncome
 * @package App\Console\Commands
 */

class PayNotify extends Command
{

    protected $signature = 'command:pay-notify';

    protected $description = 'Command description';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        while (1){

            $member_order = MemberOrder::where('notify_pay', '0')->where('is_pay', '0')->where(function ($query) {
                $query->orWhere('payment_type', '支付宝支付')->orWhere('payment_type', '微信支付');
            })->orderBy('id', 'DESC')->first();

            if ($member_order){

                if ($member_order->payment_type == '支付宝支付') {

                }elseif ($member_order->payment_type == '微信支付') {
                    $wechat = Pay::wechat([
                        'app_id' => env('WECHAT_APPID'),
                        'mch_id' => env('WECHAT_MCH_ID'),
                        'key' => env('WECHAT_KEY'),
                    ]);
                    $order = [
                        'out_trade_no' => $member_order->order_no,
                    ];
                    $result = $wechat->find($order);
                    $callback = $result->all();
                    if ($callback['result_code'] === 'SUCCESS' && $callback['trade_state'] === 'SUCCESS' && $callback['total_fee'] == $member_order->money * 100) {
                        $memberOrderController = new MemberOrderController();
                        // 修改支付状态
                        if ($callback['attach'] == 1  || $callback['attach'] == 3){
                            //门店消费
                            $memberOrderController->consume($callback);
                        }

                    } else {
                        // 修改支付状态
                        $member_order->notify_pay = 1;
                        $member_order->save();
                    }
                }

            }else{
                echo 'game over';
                sleep(10);
            }


        }


    }
}
